package com.algorithm.hqy;

/**
 * @Classname DoubleLinkedList
 * @Date 2019/9/18 9:20
 * @auther by hqy
 */
public class DoubleLinkedList<T> {
    private DoubleLinkedNode head = new DoubleLinkedNode<T>() {
        @Override
        public int compare(T t) {
            return -1;
        }
    };

    public void addSort(DoubleLinkedNode doubleLinkedNode) {
        DoubleLinkedNode temp = head;


        while (true) {
            if (temp.next == null) {
                temp.next = doubleLinkedNode;
                doubleLinkedNode.pre = temp;
                break;
            }
            if (temp.next.compare(doubleLinkedNode) > 0) {
                doubleLinkedNode.next = temp.next;
                doubleLinkedNode.pre = temp;
                temp.next = doubleLinkedNode;
                break;
            }
            temp = temp.next;

        }

    }

    public void addNoSort(DoubleLinkedNode doubleLinkedNode) {
        DoubleLinkedNode temp = head;

        while (true) {

            if (temp.next == null) {
                temp.next = doubleLinkedNode;
                doubleLinkedNode.pre = temp;
                break;
            }
            temp = temp.next;
        }
    }

    public void delNode(DoubleLinkedNode doubleLinkedNode) {
        DoubleLinkedNode temp = head;
        while (temp.next!=null) {
            if (temp.next == null) {
                System.out.println("没有找到目标节点");
                break;
            }
            if (temp.next.compare(doubleLinkedNode) == 0) {
                temp.next = temp.next.next;
                temp.next.next.pre = temp;
                break;
            }
            temp = temp.next;
        }
    }

    public void show() {
        DoubleLinkedNode temp = head.next;

        while (true) {
            if (temp == null) {
                System.out.println("没有啦~~~");
                break;
            } else {
                System.out.println(temp);
            }

            temp = temp.next;
        }

    }

    public DoubleLinkedNode getIndex(int index) {
        DoubleLinkedNode temp = head;

        for (int i = 0; i <= index; i++) {
            if (temp == null) {
                return null;
            }
            temp = temp.next;
        }
        return temp;

    }

    public void reverse() {
        DoubleLinkedNode helper = new DoubleLinkedNode() {
            @Override
            public int compare(Object o) {
                return -1;
            }
        };
        DoubleLinkedNode temp = head.next;

        while (temp != null) {

            DoubleLinkedNode next = temp.next;
            temp.next = helper.next;
            helper.next = temp;
            temp = next;
        }
        head.next = helper.next;
    }


}

abstract class DoubleLinkedNode<T> {
    public DoubleLinkedNode next;
    public DoubleLinkedNode pre;

    public abstract int compare(T t);


}
